# chatbot.py
# coding:utf-8
# encoding='utf-8'
from flask import Flask, Blueprint, request, jsonify
from datetime import timedelta
import pandas as pd
import jieba
import warnings
import os

# 忽略警告信息
warnings.filterwarnings('ignore')

# 创建Flask应用
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)

# 调试：打印当前工作目录
print(f"当前工作目录: {os.getcwd()}")

# 定义文件路径（使用绝对路径）
file_path = "C:/Users/16201/PycharmProjects/pythonProject19/my_flask_app/app/model/智能问答.csv"

# 调试代码：检查文件路径和权限
print(f"文件路径: {file_path}")
print(f"文件是否存在: {os.path.exists(file_path)}")
print(f"是否有读取权限: {os.access(file_path, os.R_OK)}")

# 检查文件是否存在以及是否有读取权限
if not os.path.exists(file_path):
    raise FileNotFoundError(f"文件不存在: {file_path}")
if not os.access(file_path, os.R_OK):
    raise PermissionError(f"没有读取文件的权限: {file_path}")

# 加载数据
df = pd.read_csv(file_path, encoding='utf-8')

# 定义函数
def re_pipei_word(text):
    sentence_corpus = df['用户'].values[:200]
    input_sentence = text
    corpus_tokens = [set(jieba.lcut(sentence)) for sentence in sentence_corpus]
    input_tokens = set(jieba.lcut(input_sentence))

    similarities = [len(input_tokens.intersection(tokens)) / len(input_tokens.union(tokens)) for tokens in corpus_tokens]
    most_similar_index = similarities.index(max(similarities))
    most_similar_sentence = sentence_corpus[most_similar_index]
    return most_similar_sentence

# 创建chatbot蓝图
chatbot_bp = Blueprint('chatbot', __name__)

@chatbot_bp.route('/chatbot', methods=['POST'])
def chatbot():
    data = request.json
    input_sentence = data.get('message')
    if not input_sentence:
        return jsonify({'response': '请输入有效的消息'}), 400

    response = re_pipei_word(input_sentence)
    row_data = df[df['用户'] == response]
    answer = row_data['客服'].values[0]
    return jsonify({'response': answer}), 200

# 注册蓝图
app.register_blueprint(chatbot_bp)
#
# # 运行Web服务器
# if __name__ == '__main__':
#     app.run(port=5001, debug=False)
